/*
 * This file is part of ELCube.
 *
 * ELCube is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ELCube is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with ELCube.  If not, see <https://www.gnu.org/licenses/>.
 */
package cn.nkpro.elcube.task;

import cn.nkpro.elcube.task.from.NkCustomFormFieldType;
import cn.nkpro.elcube.task.from.NkFunctionValidator;
import cn.nkpro.elcube.task.model.BpmFormFieldValidationConstraint;
import org.camunda.bpm.engine.impl.ProcessEngineImpl;
import org.camunda.bpm.engine.impl.form.type.AbstractFormFieldType;
import org.camunda.bpm.engine.impl.form.validator.FormFieldValidator;
import org.camunda.bpm.engine.spring.SpringProcessEngineConfiguration;
import org.camunda.bpm.spring.boot.starter.annotation.EnableProcessApplication;
import org.camunda.bpm.spring.boot.starter.util.SpringBootProcessEnginePlugin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.*;
import java.util.stream.Collectors;

@Configuration
@EnableProcessApplication
public class CamundaConfiguration extends SpringBootProcessEnginePlugin {

    @Autowired
    private List<NkCustomFormFieldType> customFormFieldTypes;

    @Override
    public void preInit(SpringProcessEngineConfiguration processEngineConfiguration) {
        super.preInit(processEngineConfiguration);

        processEngineConfiguration.setIdGenerator(new NkBpmIdGenerator());

        List<AbstractFormFieldType> collect = customFormFieldTypes.stream()
                .filter(e->e instanceof AbstractFormFieldType)
                .map(e->(AbstractFormFieldType)e)
                .collect(Collectors.toList());

        processEngineConfiguration.setCustomFormTypes(collect);

        Map<String, Class<? extends FormFieldValidator>> validator = new HashMap<>();
        validator.put("function",NkFunctionValidator.class);
        processEngineConfiguration.setCustomFormFieldValidators(validator);

    }

    @Override
    public void postInit(SpringProcessEngineConfiguration processEngineConfiguration) {
        super.postInit(processEngineConfiguration);
    }

    @Override
    public void postProcessEngineBuild(ProcessEngineImpl processEngine) {
        super.postProcessEngineBuild(processEngine);
    }
}
